package com.media.controller;

import com.media.response.RestResponse;
import com.media.service.MediaFilesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RestController
@Api(tags = "大文件上传接口")
@RequestMapping("/upload")
public class BigUploadController {

    @Autowired
    private MediaFilesService mediaFilesService;

    @Api(value = "大文件上传接口", tags = "大文件上传接口")
    @RestController
    public class BigFilesController {


        @ApiOperation(value = "文件上传前检查文件")
        @PostMapping("/upload/checkfile")
        public RestResponse<Boolean> checkfile(@RequestParam("fileMd5") String fileMd5) throws Exception {
            RestResponse<Boolean> b=  mediaFilesService.checkFile(fileMd5);
            return b;
        }


        @ApiOperation(value = "分块文件上传前的检测")
        @PostMapping("/upload/checkchunk")
        public RestResponse<Boolean> checkchunk(@RequestParam("fileMd5") String fileMd5, @RequestParam("chunk") int chunk) throws Exception {
            //检测当前分块是否存在
            RestResponse<Boolean> b =   mediaFilesService.checkChunk(fileMd5, chunk);
            return b;
        }

        @ApiOperation(value = "上传分块文件")
        @PostMapping("/upload/uploadchunk")
        public RestResponse<Boolean> uploadchunk(@RequestParam("file") MultipartFile file, @RequestParam("fileMd5") String fileMd5, @RequestParam("chunk") int chunk) throws Exception {
            //前端将大文件给分片了，后端根据前端传的当前分块索引和分块文件，将分块上传到minio中
            //创建临时文件
            File tempFile = File.createTempFile("minio", "temp");

            //将文件写入临时文件
            file.transferTo(tempFile);
            String absoluteFile = tempFile.getAbsolutePath();
            RestResponse<Boolean> b = mediaFilesService.uploadChunk(absoluteFile, fileMd5, chunk);
            return b;
        }

        @ApiOperation(value = "合并文件")
        @PostMapping("/upload/mergechunks")
        public RestResponse<Boolean> mergechunks(@RequestParam("fileMd5") String fileMd5, @RequestParam("fileName") String fileName, @RequestParam("chunkTotal") int chunkTotal) throws Exception {
            return mediaFilesService.mergechunks(fileMd5, fileName, chunkTotal);
        }

    }
}
